package com.example.myapplication.function.keyboard

import android.util.Log

class SimplePianoSoundGenerator {
    
    companion object {
        private const val SAMPLE_RATE = 44100
        private const val DURATION = 1.5 // 缩短持续时间
        
        // 常用音符频率表
        private val COMMON_NOTE_FREQUENCIES = mapOf(
            "C3" to 130.81, "D3" to 146.83, "E3" to 164.81, "F3" to 174.61, "G3" to 196.00, "A3" to 220.00, "B3" to 246.94,
            "C4" to 261.63, "D4" to 293.66, "E4" to 329.63, "F4" to 349.23, "G4" to 392.00, "A4" to 440.00, "B4" to 493.88,
            "C5" to 523.25, "D5" to 587.33, "E5" to 659.25, "F5" to 698.46, "G5" to 783.99, "A5" to 880.00, "B5" to 987.77
        )
    }
    
    /**
     * 生成简化的钢琴音色（确保能正常生成）
     */
    fun generatePianoNote(noteName: String): PianoSoundGenerator.PianoNote {
        val frequency = COMMON_NOTE_FREQUENCIES[noteName]
            ?: throw IllegalArgumentException("Unsupported note: $noteName")
        
        val sampleCount = (SAMPLE_RATE * DURATION).toInt()
        val samples = FloatArray(sampleCount)
        
        // 简化的声音生成 - 只使用基频
        for (i in samples.indices) {
            val time = i.toDouble() / SAMPLE_RATE
            val envelope = calculateSimpleEnvelope(time)
            val sample = Math.sin(2.0 * Math.PI * frequency * time).toFloat()
            samples[i] = sample * envelope
        }
        
        // 确保数据有效
        if (samples.all { it == 0f }) {
            throw IllegalStateException("Generated silent audio for $noteName")
        }
        
        return PianoSoundGenerator.PianoNote(noteName, frequency, samples, DURATION)
    }
    
    private fun calculateSimpleEnvelope(time: Double): Float {
        return when {
            time < 0.1 -> (time / 0.1).toFloat() // Attack
            time < DURATION - 0.2 -> 0.8f // Sustain
            else -> {
                val releaseTime = time - (DURATION - 0.2)
                (0.8f * (1 - releaseTime / 0.2f)).coerceAtLeast(0.0).toFloat()
            }
        }
    }
    
    /**
     * 生成常用音符库
     */
    fun generateCommonSoundLibrary(): Map<String, PianoSoundGenerator.PianoNote> {
        val soundLibrary = mutableMapOf<String, PianoSoundGenerator.PianoNote>()
        
        COMMON_NOTE_FREQUENCIES.keys.forEach { noteName ->
            try {
                val note = generatePianoNote(noteName)
                soundLibrary[noteName] = note
                Log.d("SimpleSoundGen", "Generated: $noteName (${note.frequency}Hz)")
            } catch (e: Exception) {
                Log.e("SimpleSoundGen", "Failed to generate $noteName: ${e.message}")
            }
        }
        
        return soundLibrary
    }
}